
///*------------------------------------------------------------------------
////                          Project CommonLib                           //
//------------------------------------------------------------------------*/

#include "stdafx.h"
#include "CmCipher.h"

#pragma pack(push, 1)


namespace CommonLib
{

void Decrypt(unsigned char *buf, const DWORD *key, const size_t&  length)
{	
	char source=NULL, oldBuf=NULL;
	char *strKey = (char *)key;

	source = buf[3];
	buf[3] = buf[3] ^ strKey[2];
	oldBuf = buf[2];
	buf[2] = buf[2] ^ source ^ strKey[3];
	source = oldBuf;
	oldBuf = buf[1];
	buf[1] = buf[1] ^ source ^ strKey[4];
	source = oldBuf;
	buf[0] = buf[0] ^ source ^ strKey[5];

	source = buf[0];
	buf[0] = buf[0] ^ strKey[0];
	for (size_t i = 1; i < length; ++i) 
	{
		oldBuf = buf[i];
		buf[i] = buf[i] ^ source ^ strKey[i & 7];
		source = oldBuf;
	}
}

void Encrypt(unsigned char *buf, const DWORD *key, const size_t& length)
{
	char *strKey = (char *)key;	

	buf[0] = buf[0] ^ strKey[0];
	for (size_t i = 1; i < length; ++i) 
	{
		buf[i] = buf[i] ^ buf[i - 1] ^ strKey[i & 7];
	}

	buf[3] = buf[3] ^ strKey[2];
	buf[2] = buf[2] ^ buf[3] ^ strKey[3];
	buf[1] = buf[1] ^ buf[2] ^ strKey[4];
	buf[0] = buf[0] ^ buf[1] ^ strKey[5];
}


}


#pragma pack(pop)


///*------------------------------------------------------------------------
//
//------------------------------------------------------------------------*/
